package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-release/middle"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Release struct {
	//ID         uint   `gorm:"primaryKey"`
	VersionNo  string `gorm:"primaryKey" json:"versionNo"`
	AccessLink string `json:"accessLink"`
	Username   string `json:"username"`
	Password   string `json:"password"`
	Status     int    `json:"status"`
}

var db *gorm.DB

func main() {
	r := gin.Default()

	r.Use(middle.Cors())

	// Connect to SQLite database
	var err error
	db, err = gorm.Open(sqlite.Open("releases.db"), &gorm.Config{})
	if err != nil {
		panic("Failed to connect to database")
	}

	// Auto Migrate the database
	db.AutoMigrate(&Release{})

	// Set up routes
	r.GET("/api/releases", getReleases)
	r.POST("/api/release", addRelease)
	r.PUT("/api/release/:versionNo", updateRelease)
	r.DELETE("/api/release/:versionNo", deleteRelease)

	// Serve the frontend Vue app
	//r.Static("/", "./frontend/dist")

	// Run the server
	r.Run(":8081")
}

func getReleases(c *gin.Context) {
	var releases []Release
	db.Find(&releases)
	fmt.Println(releases)
	c.JSON(200, releases)
}

func addRelease(c *gin.Context) {
	var release Release
	if err := c.BindJSON(&release); err != nil {
		fmt.Println("Error binding JSON:", err)
		c.JSON(400, gin.H{"error": "Invalid request payload"})
		return
	}

	db.Create(&release)
	c.JSON(200, release)
}

func updateRelease(c *gin.Context) {
	versionNo := c.Params.ByName("versionNo")
	var release Release
	if err := db.Where("version_no = ?", versionNo).First(&release).Error; err != nil {
		c.JSON(404, gin.H{"error": "Release not found"})
		return
	}

	var updatedRelease Release
	if err := c.BindJSON(&updatedRelease); err != nil {
		c.JSON(400, gin.H{"error": "Invalid request payload"})
		return
	}

	// 更新 release 对象的字段
	release.AccessLink = updatedRelease.AccessLink
	release.Username = updatedRelease.Username
	release.Password = updatedRelease.Password
	release.Status = updatedRelease.Status

	db.Save(&release)
	c.JSON(200, release)
}

func deleteRelease(c *gin.Context) {
	versionNo := c.Params.ByName("versionNo")
	var release Release
	if err := db.Where("version_no = ?", versionNo).First(&release).Error; err != nil {
		c.JSON(404, gin.H{"error": "Release not found"})
		return
	}

	db.Delete(&release)
	c.Status(200)
}
